package cn.kgc.count.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Repository;

import java.util.*;

/**
 * Created by teacher ZHANG on 2022/12/1
 */
@Repository
public class CountDaoImpl implements CountDao {
    @Autowired
    private StringRedisTemplate redisTemplate;

    //将数据加入hyperLog中
    @Override
    public void hyperLogAdd(String key, String value) {
        redisTemplate.opsForHyperLogLog().add(key, value);
    }

    //读取hyperLog中的元素数量
    @Override
    public Integer hyperLogCount(String key) {
        return redisTemplate.opsForHyperLogLog().size(key).intValue();
    }

    //根据pattern样式取所有的键名
    @Override
    public Set<String> keys(String pattern) {
        return redisTemplate.keys(pattern);
    }

    @Override
    public void zsetAdd(String key, String value, Integer score) {
        redisTemplate.opsForZSet().add(key, value, score);
    }

    @Override
    public List<Map<String, Integer>> zsetRevrange(String key, Integer num) {
        List<Map<String, Integer>> maps = new ArrayList<>();

        Set<ZSetOperations.TypedTuple<String>> tuples = redisTemplate.opsForZSet().reverseRangeWithScores(key, 0, num - 1);
        for (ZSetOperations.TypedTuple<String> tuple : tuples) {
            Map<String, Integer> map = new HashMap<>();
            map.put("value", Integer.parseInt(tuple.getValue()));
            map.put("score", tuple.getScore().intValue());

            maps.add(map);
        }

        return maps;
    }


}
